package leetcode.method.monotone_stack;

import java.util.Deque;
import java.util.LinkedList;

public class Program42CatchRain {

    public Program42CatchRain() {

    }

    public int trap(int[] height) {
        return office(height);
    }

    // i,i + 1是按序入栈，i和 i+1的值相等会多余计算一次i+ 1出栈时currHeight = 0;
    public int office(int[] height) {
        int ans = 0;
        Deque<Integer> stack = new LinkedList<Integer>();
        int n = height.length;
        for (int i = 0; i < n; ++i) {
            while (!stack.isEmpty() && height[i] > height[stack.peek()]) {
                // 进入循环 i为右侧值

                int top = stack.pop(); //当前低点
                if (stack.isEmpty()) {
                    break;
                }
                int left = stack.peek();// 左侧值
                int currWidth = i - left - 1;
                int currHeight = Math.min(height[left], height[i]) - height[top];
                ans += currWidth * currHeight;
            }
            stack.push(i);
        }
        return ans;

    }

    public static void main(String[] args) {

        Program42CatchRain obj = new Program42CatchRain();

        System.out.println();
    }
}
